package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    WeChatProperties weChatProperties;

    private final String WX_loginURL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信登陆功能
     * @param dto
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        log.info("微信用户{}登录",dto);
        //检验用户微信账号

        String openid = getOpenid(dto);

        //校验失败，退出
        if(Objects.isNull(openid)){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //获取用户登录对象
        User user = userMapper.getByOpenId(openid);
        if(Objects.isNull(user)){
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.addUser(user);
        }
        //获取Jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //封装VO对象
        return UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(jwt)
                .build();
    }

    private String getOpenid(UserLoginDTO dto) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", dto.getCode());
        paramMap.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_loginURL, paramMap);
        JSONObject jsonObject = JSON.parseObject(json);
        return (String) jsonObject.get("openid");
    }
}
